package com.lemurian.bankdata.action.business;

import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.apache.struts2.ServletActionContext;
import org.apache.struts2.interceptor.validation.SkipValidation;
import org.hibernate.criterion.MatchMode;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Restrictions;
import org.springframework.beans.factory.annotation.Autowired;

import com.lemurian.bankdata.dto.LogHelper;
import com.lemurian.bankdata.lite.authentication.BankDataPrincipal;
import com.lemurian.bankdata.lite.enums.UserActivityType;
import com.lemurian.bankdata.lite.logger.BankDataLogger;
import com.lemurian.bankdata.lite.struts.Pager;
import com.lemurian.bankdata.lite.struts.PartialList;
import com.lemurian.bankdata.lite.utils.GeneralConstant;
import com.lemurian.bankdata.lite.utils.GlobalFunction;
import com.lemurian.bankdata.services.ActivityLogService;
import com.lemurian.bankdata.services.BPNRegionListService;
import com.lemurian.bankdata.services.CourierService;
import com.lemurian.bankdata.utils.BaseAction;
import com.lemurian.entity.BPNRegionList;
import com.lemurian.entity.Courier;
import com.lemurian.entity.User;
import com.opensymphony.xwork2.Preparable;

@SuppressWarnings("serial")
public class KurirAction extends BaseAction implements Preparable {

	private BankDataLogger log = BankDataLogger.getLogger(KurirAction.class.getSimpleName());
	
	private int id = 0;
	private Courier kurir = null;
	private List<Courier> listKurir = new ArrayList<Courier>();
	
	private String namaKurir = "";
	
	private int wilayahId = 0;
	//private BPNRegionList wilayahBpn = null;
	private List<BPNRegionList> listWilayahBpn = new ArrayList<BPNRegionList>();
		
	private User user;
	private BankDataPrincipal principal;
	
	@Autowired private BPNRegionListService bpnRegionListService;
	@Autowired private CourierService courierService;
	
	@Autowired 
	private ActivityLogService userActivityLogService;
	private LogHelper userActivityLog;
	
	@Override
	public void prepare() throws Exception {
		principal = (BankDataPrincipal) getSession().get(GeneralConstant.USER_PRINCIPAL);
		user = principal.getUser();
		
		log.sInfo("get kurir id [%s]", id);
        if (id > 0) {
        	kurir = courierService.load(id);
        	if (kurir != null) {
        		log.info("found kurir with that id");
        	} else {
        		log.info("klien was not found");
        	}
        }
	}

	@Override
	@SkipValidation
	public String list() {		
		log.info("list kurir terdaftar ...");
		setPreviousPage(GeneralConstant.LIST);
		try {
			PartialList<Courier> partialList = courierService.findByCriteria(getStart(), getCount(),
					getAscDesc().equalsIgnoreCase("desc") ? Order.desc(getOrderBy().length() > 0 ? getOrderBy() : "name") : Order.asc(getOrderBy().length() > 0 ? getOrderBy() : "name"),
	                namaKurir != null && namaKurir.length() > 0 ? Restrictions.ilike("name", namaKurir, MatchMode.ANYWHERE) : Restrictions.ne("id", new Integer(-1))
					);
	
	        listKurir = partialList.getList();
	        log.sInfo("found [%s] kurir", listKurir.size());
	
	        setPager(Pager.generatePager(getStart(), getCount(), partialList.getTotal()));
	        setPagerItem(Pager.generatePagerItem(getStart(), getCount(), partialList.getTotal()));
	
	        partialList = null;
	
		} catch (Exception e) {
			e.printStackTrace();
		}
	    setMappedRequest(GeneralConstant.LIST);
	    return SUCCESS;

	}

	@Override
	@SkipValidation
	public String add() {
		log.info("on edit / add kurir ..");
	    setMappedRequest(GeneralConstant.SAVE);
	    setPreviousPage(GeneralConstant.ADD);
	    
	    getSession().put(GeneralConstant.TIME_IN_SESSION, new Date());
	    
	    try {
	    	
	    	listWilayahBpn = bpnRegionListService.findAll();
	    	log.sInfo("found wilayah [%s]", listWilayahBpn.size());
	    	
	    	if (kurir.getBpnRegion() != null) {
				wilayahId = kurir.getBpnRegion().getId();
			}			
		} catch (Exception e) {
			e.printStackTrace();
		}
	    
	    return SUCCESS;
	}

	@Override
	public String save() {
		log.info("on save kurir action .. ");
		try {
			
			String message = "";
			if(id > 0) {
				kurir.setUpdateBy(user.getLoginId());
				kurir.setUpdateDate(new Timestamp(System.currentTimeMillis()));
				
				message = "Update";
                userActivityLog = new LogHelper(user, UserActivityType.UPDATE_COURIER);
			} else {
				kurir.setCreateBy(user.getLoginId());
				kurir.setCreateDate(new Timestamp(System.currentTimeMillis()));
				
				message = "Add";
                userActivityLog = new LogHelper(user, UserActivityType.ADD_COURIER);
			}
			
			if (wilayahId != 0) {
				BPNRegionList wilayah = bpnRegionListService.findById(wilayahId);
				log.sInfo("found wilayah [%s]", wilayah.getReqionName());
				kurir.setBpnRegion(wilayah);
			}
			
			courierService.save(kurir);
			addCustomActionMessage("Data kurir berhasil disimpan");
			
			try {
                message += " " + kurir.getName() + " is success";
                addCustomActionMessage(message);
                
                log.sInfo(" :: User [%s:%s] is successfully save Kurir [%s:%s]", user.getId(), user.getName(), kurir.getId(), kurir.getName());
                userActivityLog.setStatus(LogHelper.SUCCESS_ACTIVITY);
            } catch (Exception e) {
                message += " " + kurir.getName() + " is failed, message : "+e.getMessage();
                addCustomActionError(message);
                log.sInfo(" :: Error was raised when User [%s:%s] save Kurir [%s:%s]", user.getId(), user.getName(), kurir.getId(), kurir.getName());
                
                //set activity log status into failed
                userActivityLog.setStatus(LogHelper.FAILED_ACTIVITY);
                userActivityLog.setErrorMsg(e.getMessage());
            }
            
            userActivityLog.setSessionId(ServletActionContext.getRequest().getSession().getId());
            userActivityLog.setStartDate((Date) getSession().get(GeneralConstant.TIME_IN_SESSION));
            userActivityLog.getAdditionalParams().add(kurir.getName());
            userActivityLogService.saveUserActivity(userActivityLog);
            getSession().remove(GeneralConstant.TIME_IN_SESSION);
			
		} catch (Exception e) {
			addCustomActionMessage("Maaf terjadi kesalahan : " + e.getMessage());
			e.printStackTrace();
		}

		setMappedRequestFullPath("/KurirAction_list.do");
		return GeneralConstant.REDIRECT;
	}
	

	@Override
	@SkipValidation
	public String edit() {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public String update() {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	@SkipValidation
	public String detail() {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	@SkipValidation
	public String delete() {
		try {
			courierService.delete(kurir);
			
			addCustomActionMessage("Kurir " + kurir.getName() + " berhasil dihapus");
			
			userActivityLog = new LogHelper(user, UserActivityType.DELETE_COURIER);
			
			String message = "";
            try {
                message = "Delete " + kurir.getName() + " is success";
                addActionMessage(message);
                log.sInfo(" :: User [%s:%s] is successfully delete Kurir [%s:%s]", user.getId(), user.getName(), kurir.getId(), kurir.getName());

                //check if activity is success
                userActivityLog.setStatus(LogHelper.SUCCESS_ACTIVITY);
            } catch (Exception e) {
                message = "Delete " + kurir.getName() + " is failed, message : "+e.getMessage();
                addActionError(message);
                log.sInfo(" :: Error was raised when User [%s:%s] delete Kurir [%s:%s]", user.getId(), user.getName(), kurir.getId(), kurir.getName());
                
                //set activity log status into failed
                userActivityLog.setStatus(LogHelper.FAILED_ACTIVITY);
                userActivityLog.setErrorMsg(e.getMessage());
            }
            //save activity log
            userActivityLog.setSessionId(ServletActionContext.getRequest().getSession().getId());
            userActivityLog.getAdditionalParams().add(kurir.getName());
            userActivityLogService.saveUserActivity(userActivityLog);
		} catch (Throwable t) {
			addCustomActionError(t.getMessage());
			t.printStackTrace();
		}
		setMappedRequestFullPath("KurirAction_list.do");
		return GeneralConstant.REDIRECT;
	}

	public int getId() {
		return id;
	}

	public void setId(String id) {
		int id_ = 0;
		if(id != null && !id.equalsIgnoreCase("0")) {
			id = GlobalFunction.decodeParameter(id);
	        id_ = Integer.parseInt(id);
		}
        this.id = id_;
	}

	public Courier getKurir() {
		return kurir;
	}

	public void setKurir(Courier kurir) {
		this.kurir = kurir;
	}

	public List<Courier> getListKurir() {
		return listKurir;
	}

	public void setListKurir(List<Courier> listKurir) {
		this.listKurir = listKurir;
	}

	public String getNamaKurir() {
		return namaKurir;
	}

	public void setNamaKurir(String namaKurir) {
		this.namaKurir = namaKurir;
	}

	public int getWilayahId() {
		return wilayahId;
	}

	public void setWilayahId(String wilayahId) {
		int id_ = 0;
		if(wilayahId != null && !wilayahId.equalsIgnoreCase("0")) {
			wilayahId = GlobalFunction.decodeParameter(wilayahId);
	        id_ = Integer.parseInt(wilayahId);
		}
        this.wilayahId = id_;
	}

	public List<BPNRegionList> getListWilayahBpn() {
		return listWilayahBpn;
	}

	public void setListWilayahBpn(List<BPNRegionList> listWilayahBpn) {
		this.listWilayahBpn = listWilayahBpn;
	}
	
	
}
